﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace map.Controls
{
    public partial class RandomCheckupCoding : System.Web.UI.Page
    {
        #region 页面载入
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateCheckImg();
            }
        }
        #endregion

        #region 辅助方法

        /// <summary>
        /// 生成检验码
        /// </summary>
        private void GenerateCheckImg()
        {
            string sessionKeyPrefix = "";
            int count = 4;
            if (Request["count"] != null)
            {
                try
                {
                    count = Convert.ToInt32(Request["count"]);
                }
                catch { }
            }
            if (count < 4)
                count = 4;
            if (Request["key"] != null)
                sessionKeyPrefix = Request["key"];

            GenerateRandomStrImg(GeneratorRandomCode(count ), sessionKeyPrefix);
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private string GeneratorRandomCode(int count)
        {
            string checkCode = string.Empty;
            if (count < 4)
                count = 4;

            Random random = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < count; i++)
            {
                int index = (random.Next() % 2);
                if (index == 0)
                    checkCode += random.Next(0, 10).ToString();
                else
                    checkCode += GetRandomLetter(random);
            }

            return checkCode; 
        }

        /// <summary>
        /// 获取单个随机字符
        /// </summary>
        /// <param name="random"></param>
        /// <returns></returns>
        private char GetRandomLetter(Random random)
        {
            int nChar = random.Next(65, 122);

            // 非字母ASCII段 
            if (nChar >= 91 && nChar <= 96)
            {
                nChar -= 6;
            }

            return (char)(nChar);
        }

        /// <summary>
        /// 绘制检验码
        /// </summary>
        /// <param name="checkCode"></param>
        private void GenerateRandomStrImg(string checkCode,string saveSessionKeyPrefix)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(14 * checkCode.Length, 20);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

            try
            {
                Random random = new Random(DateTime.Now.Millisecond);

                //清空背景色
                g.Clear(System.Drawing.Color.White);

                int ddCount = (int)(checkCode.Length*1.2);
                //画图片的背景噪音线 
                for (int i = 0; i < ddCount; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.FromArgb(random.Next(255), random.Next(255), random.Next(255))
                        ), x1, y1, x2, y2);
                }

                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;

                List<FontStyle> a = GetColorList(checkCode.Length);
                for (int i = 0; i < checkCode.Length; i++)
                {
                    FontStyle Ftyle = GetColor(a);
                    Font font = new System.Drawing.Font("Verdana", Ftyle.FontSize, (System.Drawing.FontStyle.Bold));
                    SolidBrush brush = new SolidBrush(Ftyle.FontColor);
                    g.DrawString(checkCode.Substring(i, 1), font, brush, GetCodeRect(i), sf);
                }
                //画图片的边框线 
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());

               
                //保存到Session中
                Session[saveSessionKeyPrefix + "_checkcode"] = checkCode;
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }


        }

        /// <summary>
        /// 从颜色列表中随机选取颜色
        /// </summary>
        /// <param name="Color_L"></param>
        /// <returns></returns>
        private FontStyle GetColor(List<FontStyle> Color_L)
        {
            Random rnd = new Random();
            int i = rnd.Next(0, Color_L.Count);
            FontStyle l = Color_L[i];
            Color_L.RemoveAt(i);
            return l;
        }

        /// <summary>
        /// 获取颜色列表
        /// </summary>
        private List<FontStyle> GetColorList(int count)
        {
            List<FontStyle> a = new List<FontStyle>();
            Color[] colors = new Color[] { Color.Red,Color.Green ,Color.Blue,Color.Black ,Color.Gray ,Color.Gold };
            Random random = new Random();
            for (int i = 0; i < count; i++)
            {
                Color cColor = colors[(random.Next(0, colors.Length) % (colors.Length))];
                a.Add(new FontStyle(cColor, 12));
            }                 
            return a;
        }

        /// <summary>
        /// 获取单个字符的绘制区域
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public Rectangle GetCodeRect(int index)
        {
            // 计算一个字符应该分配有多宽的绘制区域（等分为CodeLength份）
            int subWidth = 14;
            // 计算该字符左边的位置
            int subLeftPosition = subWidth * index;

            return new Rectangle(subLeftPosition + 1, 1, subWidth, 20);
        }
        #endregion

    }

    #region 辅助类
    /// <summary>
    /// 字体类
    /// </summary>
    public class FontStyle
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="FontColor">颜色</param>
        /// <param name="FontSize">字体大小</param>
        public FontStyle(Color FontColor, int FontSize)
        {
            _FontColor = FontColor;
            _FontSize = FontSize;
        }
        #region "Private Variables"
        private Color _FontColor;
        private int _FontSize;
        #endregion

        #region "Public Variables"
        /// <summary>
        /// 字体颜色
        /// </summary>
        public Color FontColor
        {
            get
            {
                return _FontColor;
            }
            set
            {
                _FontColor = value;
            }
        }
        /// <summary>
        /// 字体大小
        /// </summary>
        public int FontSize
        {
            get
            {
                return _FontSize;
            }
            set
            {
                _FontSize = value;
            }
        }
        #endregion
    }
    #endregion

}



